package com.erlinyou.im.web.controller.push;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.erlinyou.im.web.controller.chat.ChatMessageController;

/**
 * 华为推送
 * @author xujie
 *
 */
public class HUAWEIPushUtils {
	private static Logger log = LoggerFactory.getLogger(ChatMessageController.class);
	
	private final static String apiUrl = "https://push-api.cloud.huawei.com/v1/10523134/messages:send";
	private static String accessToken = "";
	private final static CloseableHttpClient httpClient = HttpClients.createDefault();
//	private final static String huaweiPackageName = "com.erlinyou.worldlist";
	private final static String tokenUrl = "https://login.cloud.huawei.com/oauth2/v2/token";
	
	private static long tokenExpiredTime = 0L;
	
	private final static String huaweiAppSecretKey = "7de63aeac57a86eb4b73ebd4d90591d0";
	
	private final static String huaweiAppId = "10523134";
	/**
	 * 刷新token
	 */
	public static void refreshToken() throws Exception {
	    String msgBody = MessageFormat.format(
	            "grant_type=client_credentials&client_secret={0}&client_id={1}",
	            URLEncoder.encode(huaweiAppSecretKey, "UTF-8"), huaweiAppId);
	    String response = httpPost(tokenUrl, msgBody, 5000, 5000);
	    JSONObject obj = JSONObject.parseObject(response);
	    accessToken = obj.getString("access_token");
	    tokenExpiredTime = System.currentTimeMillis() + (obj.getLong("expires_in") - 5 * 60) * 1000;

	}
	public static boolean sendRequest(String title,String content,JSONArray tokens,String pushContent) throws Exception{
			if (tokenExpiredTime <= System.currentTimeMillis()) {
			    refreshToken();
			}
			JSONObject body = new JSONObject();
			JSONObject message = new JSONObject();
			JSONObject notificationContent = new JSONObject();
			JSONObject android = new JSONObject();
			JSONObject androidNotification = new JSONObject();
			JSONObject click_action = new JSONObject();
			
			click_action.put("type", 1);
	//		click_action.put("intent", "intent://com.erlinyou.worldlist/deeplink?#Intent;scheme=pushscheme;launchFlags=0x4000000;S.name=abc;S.groupid=123456;S.message="+pushContent+";end");
			click_action.put("intent", "intent://com.erlinyou.worldlist/deeplink?#Intent;scheme=pushscheme;action=android.intent.action.VIEW;launchFlags=0x4000000;S.message="+pushContent+";end");
			
			androidNotification.put("title", "");
			androidNotification.put("body", "");
			androidNotification.put("click_action", click_action);
			
			android.put("notification", androidNotification);
			notificationContent.put("title", title);
			notificationContent.put("body", content);
			
			message.put("notification", notificationContent);
			message.put("android", android);
			message.put("token", tokens);
			
			body.put("validate_only", false);
			body.put("message", message);
			
			String MessageBody = JSON.toJSONString(body);
			
			System.out.println(MessageBody);
			
			HttpPost httpPost = new HttpPost(apiUrl);
			StringEntity entity = new StringEntity(MessageBody,"UTF-8");
			httpPost.setHeader("Authorization", "Bearer " + accessToken);
//			httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
			httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			httpPost.setEntity(entity);
			CloseableHttpResponse response = httpClient.execute(httpPost);
			String rpsContent = EntityUtils.toString(response.getEntity());
			int statusCode = response.getStatusLine().getStatusCode();
			System.out.println("HTTP Code:"+statusCode);
			if (statusCode == 200) {
			    JSONObject jsonObject = JSONObject.parseObject(rpsContent);
			    Integer code = jsonObject.getInteger("code");
			    String msg = jsonObject.getString("msg");
			    String requestId = jsonObject.getString("requestId");
			    System.out.println("HUAWEI Code:"+code);
			    if (code == 80000000) {
			        return true;
			    } else {
			    	log.error("HUAWEI Code{}"+code);
			    	log.error("HUAWEI msg{}"+msg+"  requestId{}"+requestId);
			    	throw new RuntimeException();
			    }
			}
			log.error("HTTP Code{}"+statusCode);
			throw new RuntimeException();
    }
	
	public static String httpPost(String httpUrl, String data, int connectTimeout, int readTimeout) throws IOException {
	    OutputStream outPut = null;
	    HttpURLConnection urlConnection = null;
	    InputStream in = null;

	    try {
	        URL url = new URL(httpUrl);
	        urlConnection = (HttpURLConnection) url.openConnection();
	        urlConnection.setRequestMethod("POST");
	        urlConnection.setDoOutput(true);
	        urlConnection.setDoInput(true);
	        urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	        urlConnection.setConnectTimeout(connectTimeout);
	        urlConnection.setReadTimeout(readTimeout);
	        urlConnection.connect();

	        // POST data
	        outPut = urlConnection.getOutputStream();
	        outPut.write(data.getBytes("UTF-8"));
	        outPut.flush();

	        // read response
	        if (urlConnection.getResponseCode() < 400) {
	            in = urlConnection.getInputStream();
	        } else {
	            in = urlConnection.getErrorStream();
	        }

	        List<String> lines = IOUtils.readLines(in, urlConnection.getContentEncoding());
	        StringBuffer strBuf = new StringBuffer();
	        for (String line : lines) {
	            strBuf.append(line);
	        }
	        return strBuf.toString();
	    } finally {
	        IOUtils.closeQuietly(outPut);
	        IOUtils.closeQuietly(in);
	        if (urlConnection != null) {
	            urlConnection.disconnect();
	        }
	    }
	}
	
	public static void main(String[] args) {
		try {
			refreshToken();
			JSONArray jsonArray = new JSONArray();
//			jsonArray.add("AA1P9ZdzUZc5q2EvyC8iZQ8h1wHnyM-VCJ3v3o9FUDOgCDQyQLUcyKHV3LGVZH_QxHK0MQ38vGA2aiYBLJKrjBtUpjRSFikg9STFH8iJsduOKY-GFphMu14gvJI2eIgt7w");
			jsonArray.add("0869158024653749300003656100CN01");
			String pushContent = "{\"validate_only\":false,\"message\":{\"notification\":{\"title\":\"\",\"body\":\"ghy点评了你的动态\"},\"android\":{\"notification\":{\"title\":\"\",\"body\":\"\",\"click_action\":{\"type\":1,\"intent\":\"intent://com.erlinyou.worldlist/deeplink?#Intent;scheme=pushscheme;action=android.intent.action.VIEW;launchFlags=0x4000000;S.message={\\\"count\\\":1,\\\"content\\\":{\\\"x\\\":1.2946427E7,\\\"y\\\":4844899.5,\\\"from\\\":10,\\\"to\\\":79057,\\\"nickName\\\":\\\"ghy\\\",\\\"id\\\":16651,\\\"msgType\\\":\\\"comment snapshot\\\",\\\"createTime\\\":1574765836959}};end\"}}},\"token\":[\"huawei/0868990048432937300003656100CN01\"]}}";
			boolean b = sendRequest(new String(" ".getBytes("UTF-8")), new String("测试标题".getBytes("UTF-8")),jsonArray,pushContent);
			System.out.println(b);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
